package com.huweilong.tingshu.servlet.track;

import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huweilong.tingshu.service.TrackService;
import com.huweilong.tingshu.util.Log;
import com.huweilong.tingshu.view_object.ListTrackVO;
import com.huweilong.tingshu.view_object.StudioTrackListVO;
import com.huweilong.tingshu.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author 是阿秋啊
 * @date 2022/07/21 09:52
 **/
@WebServlet("/studio/track/list.json")
public class ListJsonServlet extends HttpServlet {
    private final TrackService trackService = new TrackService();
    private final ObjectMapper objectMapper = new ObjectMapper();
    public ListJsonServlet() {
        // 目的是序列化出的JSON带有空格和换行,可以不写
        objectMapper.setDefaultPrettyPrinter(new DefaultPrettyPrinter());
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Log.println("访问 GET /studio/track/list.json");

        req.setCharacterEncoding("utf-8");
        int page;
        String pageString = req.getParameter("page");
        if (pageString == null || pageString.trim().isEmpty()) {
            // 默认第一页
            Log.println("请求参数没有页码信息，默认首页");
            page = 1;
        }else {
            pageString = pageString.trim();
            try {
                page = Integer.parseInt(pageString);
            }catch (NumberFormatException e){
                Log.println("请求信息不是数字，默认首页");
                page = 1;
            }
        }
        StudioTrackListVO resultView = new StudioTrackListVO();
        // 1.获取当前用户
        HttpSession session = req.getSession(false);
        UserVO currentUser = null;
        if (session != null) {
            currentUser = (UserVO) session.getAttribute("currentUser");
        }
        // 2.是否登录
        if(currentUser == null) {
            Log.println("用户未登录");
            resultView.currentUser=null;
            resultView.trackList=null;
        }else {
            Log.println("用户已登录" + currentUser);
            resultView = trackService.listOfUser(currentUser,page);
        }

        Log.println("JSON序列化对象"+resultView);
        // 使用Jackson提供代码,将list对象,转化成字符串类型的,JSON格式
        String json = objectMapper.writeValueAsString(resultView);
        Log.println("JSON 序列化后"+json);
        // 响应字符串
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        Log.println("JSON写入响应体");
        writer.println(json);
    }
}